package com.lanou.zakerproject.hotspot;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lanou.zakerproject.R;
import com.lanou.zakerproject.base.VolleySingleton;
import com.lanou.zakerproject.tool.GsonRequest;
import com.lanou.zakerproject.ui.PullToRefreshBase;
import com.lanou.zakerproject.ui.PullToRefreshBase.OnRefreshListener;
import com.lanou.zakerproject.ui.PullToRefreshListView;
import com.lanou3g.greendaodemo.entity.greendao.DaoSingleton;
import com.lanou3g.greendaodemo.entity.greendao.NewsDataEntity;
import com.lanou3g.greendaodemo.entity.greendao.NewsDataEntityDao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by dllo on 16/1/8.
 */
public class HotspotFragment extends Fragment {
    private ListView listView;
    private HotSpotAdapter hotSpotAdapter;
    private Context context;
    private NewsData datas;
    List<NewsDataEntity> newsDataEntityList;
    private String url = "http://hotphone.myzaker.com/daily_hot_new.php?_appid=AndroidPhone&_bsize=1080_1920&_dev=62&_lat=38.889835&_lbs_city=%E5%A4%A7%E8%BF%9E&_lbs_province=%E8%BE%BD%E5%AE%81%E7%9C%81&_lng=121.550516&_mac=38%3Abc%3A1a%3Afb%3A42%3A78&_mcode=837226A3&_net=wifi&_nudid=e0e5c2bb5e46318d&_os=4.4.4_m1note&_os_name=m1note&_udid=867348020345406&_v=6.4.6&_version=6.45&act=pre&last_time=1453686185&rank=124041";
    NewsDataEntityDao newsDataEntityDao = DaoSingleton.getInstance().getNewsDataEntityRecommendDao();

    private PullToRefreshListView mPullListView;
    private SimpleDateFormat mDateFormat = new SimpleDateFormat("MM-dd HH:mm");
    private boolean mIsStart = true;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_hotspot, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPullListView = (PullToRefreshListView) getActivity().findViewById(R.id.listView_hotspot);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView = mPullListView.getRefreshableView();
        // 上拉加载不可用
        mPullListView.setPullLoadEnabled(false);
        // 滚动到底自动加载可用
        mPullListView.setScrollLoadEnabled(true);
        getRequsetData(url);

        mPullListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                mIsStart = true;
                new GetDataTask().execute();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                mIsStart = false;
                new GetDataTask().execute();
            }
        });
        setLastUpdateTime();

        mPullListView.doPullRefreshing(true, 500);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                String pk = datas.getData().getArticles().get(position).getPk();
                intent.putExtra("pk", pk);
                intent.setClass(context, HotSpotDetailActivity.class);
                startActivity(intent);
            }
        });
    }

    private class GetDataTask extends AsyncTask<Void, Void, NewsData> {

        @Override
        protected NewsData doInBackground(Void... params) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            }
            return datas;
        }

        @Override
        protected void onPostExecute(NewsData result) {
            boolean hasMoreData = true;
            if (mIsStart) {
                getRequsetData(url);
            }
//            hotSpotAdapter.notifyDataSetChanged();
            mPullListView.onPullDownRefreshComplete();
            mPullListView.onPullUpRefreshComplete();
            mPullListView.setHasMoreData(hasMoreData);
            setLastUpdateTime();
            super.onPostExecute(result);
        }
    }

    private void setLastUpdateTime() {
        String text = formatDateTime(System.currentTimeMillis());
        mPullListView.setLastUpdatedLabel(text);
    }

    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }

        return mDateFormat.format(new Date(time));
    }

    /**
     * 解析数据的方法
     *
     * @param urls 接口
     */
    private void getRequsetData(String urls) {
        GsonRequest<NewsData> gsonRequest = new GsonRequest<>(urls, NewsData.class, new Response.Listener<NewsData>() {
            @Override
            public void onResponse(NewsData response) {
                hotSpotAdapter = new HotSpotAdapter(getActivity(), response, 1);
                listView.setAdapter(hotSpotAdapter);
                datas = response;
                if (newsDataEntityDao.queryBuilder().list() != null) {
                    newsDataEntityDao.deleteAll();
                    addDB(response);
                } else {
                    addDB(response);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                newsDataEntityList = newsDataEntityDao.queryBuilder().list();
                hotSpotAdapter = new HotSpotAdapter(getActivity(), newsDataEntityList, 0);
                listView.setAdapter(hotSpotAdapter);
            }
        });
        VolleySingleton.getInstance()._addRequest(gsonRequest);
    }

    public void addDB(NewsData newsData) {
        newsDataEntityList = new ArrayList<>();
        for (int i = 0; i < newsData.getData().getArticles().size(); i++) {
            NewsDataEntity newsDataEntity = new NewsDataEntity();
            newsDataEntity.setTitle(newsData.getData().getArticles().get(i).getTitle());
            newsDataEntity.setAuther_name(newsData.getData().getArticles().get(i).getAuther_name());
            newsDataEntity.setList_dtime(newsData.getData().getArticles().get(i).getList_dtime());
            newsDataEntity.setItem_type(newsData.getData().getArticles().get(i).getSpecial_info().getItem_type());
            newsDataEntityList.add(newsDataEntity);
        }
        newsDataEntityDao.insertInTx(newsDataEntityList);
    }

}
